import datetime

import pandas as pd

import Global


class Futures:
    code = ""
    nowPrice = 0.0

    oldDayData = pd.DataFrame({})  # 历史日数据 多
    oldMinData = pd.DataFrame({})  # 历史分钟数据 多

    nowMinData = pd.DataFrame({})  # 最新分钟数据 单
    nowDayData = pd.DataFrame({})  # 最新日数据 单

    nowData = pd.DataFrame({})  # 当前数据 单

    futureAllMinData = pd.DataFrame({})  # 未来所有分钟数据
    futureDayData = pd.DataFrame({})  # 未来日数据
    toDayFutureMinData = pd.DataFrame({})  # 当天未来分钟数据
    toDayOldMinData = pd.DataFrame({})
    nowDate = 0

    def __init__(self, code):
        self.code = code
        self.getAllData()
        Global.futuresList.append(self)

    def getAllData(self):
        end = datetime.datetime.strptime(Global.startDate, '%Y-%m-%d')

        end = end - datetime.timedelta(days=1)  # 获取到开始前一天
        start = end - datetime.timedelta(days=30)  # 设置结束在开始前200天的日期
        self.oldMinData = Global.getFuturesData(self.code, start, end)  # 获取历史股价
        self.nowPrice = float(self.oldMinData.open.values[-1])  # 设置最新价格

        self.futureAllMinData = Global.getFuturesData(self.code, Global.startDate, Global.endDate)  # 获取未来数据
        self.getOldDayData()
        self.getFutureDayData()

    def getOldDayData(self):  # 计算历史日数据
        start = self.oldMinData.date.values[0]
        end = self.oldMinData.date.values[-1]
        date = datetime.datetime.strptime(start, '%Y-%m-%d')
        for day in range(0, Global.dayNum(start, end) + 1):
            dayData = self.oldMinData[self.oldMinData["date"] == str(date.date())]
            dayData = dayData.reset_index(drop=True)
            date += datetime.timedelta(days=1)  # 下一天
            if len(dayData) == 0:
                continue
            newDataFrame = {'date': dayData.date.values[0],
                            'open': dayData.open.values[0],
                            'high': dayData.high.max(),
                            'low': dayData.low.min(),
                            'close': dayData.close.values[-1],
                            'volume': dayData.volume.sum(),
                            'value': dayData.value.sum(),
                            }

            newDataFrame = pd.DataFrame(newDataFrame, index=[0])
            self.oldDayData = pd.concat([self.oldDayData, newDataFrame], ignore_index=True)

    def getFutureDayData(self):  # 计算未来日数据
        start = self.futureAllMinData.date.values[0]
        end = self.futureAllMinData.date.values[-1]
        date = datetime.datetime.strptime(start, '%Y-%m-%d')
        for day in range(0, Global.dayNum(start, end) + 1):
            dayData = self.futureAllMinData[self.futureAllMinData["date"] == str(date.date())]
            dayData = dayData.reset_index(drop=True)
            date += datetime.timedelta(days=1)  # 下一天
            if len(dayData) == 0:
                continue
            newDataFrame = {'date': dayData.date.values[0],
                            'open': dayData.open.values[0],
                            'high': dayData.high.max(),
                            'low': dayData.low.min(),
                            'close': dayData.close.values[-1],
                            'volume': dayData.volume.sum(),
                            'value': dayData.value.sum(),
                            }

            newDataFrame = pd.DataFrame(newDataFrame, index=[0])
            self.futureDayData = pd.concat([self.futureDayData, newDataFrame], ignore_index=True)

    def nextDay(self):  # 下一日
        for user in Global.userList:
            user.reloadAllMoney()
        if len(Global.futuresList) == 0:  # 期货为空
            return False
        if len(self.futureDayData) == 0:  # 是否遍历完未来
            return False

        for user in Global.userList:
            user.startEntrust()  # 执行委托

        self.oldDayData = pd.concat([self.oldDayData, self.futureDayData[0:1]], ignore_index=True)
        self.futureDayData = self.futureDayData[1:]
        self.nowDayData = self.oldDayData[-1:]  # 设置当前日数据
        self.nowPrice = float(self.oldDayData.close.values[-1])  # 设置最新价格
        self.nowDate = self.oldDayData.date.values[-1]  # 更新日期
        self.toDayFutureMinData = self.futureAllMinData[self.futureAllMinData["date"] == self.nowDate]  # 设置当天的所有分钟数据

        for user in Global.userList:
            user.startEntrust()  # 执行委托

        return True

    def nextMin(self):

        if len(Global.futuresList) == 0:  # 期货为空
            return False
        if len(self.toDayFutureMinData) == 0:  # 是否遍历完当日未来
            return False

        for user in Global.userList:
            user.reloadAllMoney()
            user.startEntrust()  # 执行委托

        self.oldMinData = pd.concat([self.oldMinData, self.toDayFutureMinData[0:1]], ignore_index=True)

        self.nowPrice = self.oldMinData.close.values[-1]
        self.toDayFutureMinData = self.toDayFutureMinData[1:]
        self.toDayFutureMinData = self.toDayFutureMinData.reset_index(drop=True)  # 设置排序

        self.nowMinData = self.oldMinData[-1:]  # 设置当前分钟数据

        for user in Global.userList:
            user.startEntrust()  # 执行委托

        return True
